package org.jeecg.common.converter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.SpringContextUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;

/**
 * ie下使用的消息转换器
 * ie6,7,8不支持返回application/json
 *
 * @author lixingxing
 */
@Slf4j
public class IeMappingJackson2HttpMessageConverter extends AbstractHttpMessageConverter {

    private final ObjectMapper mapper;

    public IeMappingJackson2HttpMessageConverter(ObjectMapper objectMapper) {
        super(MediaType.parseMediaType("text/html;charset=UTF-8"));
        this.mapper = objectMapper;
    }

    @Override
    protected boolean supports(Class aClass) {
        String userAgent = SpringContextUtils.getHttpServletRequest().getHeader(HttpHeaders.USER_AGENT);
        return userAgent.contains("MSIE 6.0") || userAgent.contains("MSIE 7.0") || userAgent.contains("MSIE 8.0") || userAgent.contains("MSIE 9.0");
    }

    @Override
    protected Object readInternal(Class aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        return JSON.parseObject(httpInputMessage.getBody(), aClass);
    }

    @Override
    protected void writeInternal(Object o, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
        JsonGenerator generator = this.mapper.getFactory().createGenerator(httpOutputMessage.getBody(), JsonEncoding.UTF8);
        this.mapper.writeValue(generator, o);
        generator.flush();
    }
}
